package com.lyn.kit;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcConstants;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.AnsiSqlDialect;
import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;


public class DatabaseKit {
	public static void connect() {
		PropKit.use("application-local.properties"); //读配置文件
		
		String url = PropKit.get("spring.datasource.url"); //获取url
		String username = PropKit.get("spring.datasource.username"); //获取用户名
		String password = PropKit.get("spring.datasource.password"); //获取密码
		String driverClass = PropKit.get("spring.datasource.driver-class-name"); //获取
		//创建druid插件
		DruidPlugin druidPlugin = new DruidPlugin(url, username, password, driverClass);
		
		druidPlugin.addFilter(new StatFilter()); //配置状态监控的filter
		
		int initialSize = 10; //初始连接池大小
		int minIdle = 10; //最小空闲连接数
		int maxActive = 20; //最大活跃连接数
		druidPlugin.set(initialSize, minIdle, maxActive); //配置连接池
		boolean showSql = true;
		
		//渲染json时是否小写
		boolean toLowerCase = true;
			
		Dialect dialect = null;	//数据库方言，用于支持特定数据库的特殊sql语法
		
		//根据url连接配置设置来判定数据库类型和应使用的数据库方言
		if(url.toLowerCase().contains(JdbcConstants.ORACLE)){
			dialect = new OracleDialect();
			druidPlugin.setValidationQuery("select 1 from dual");
		}
		else if(url.toLowerCase().contains(JdbcConstants.SQL_SERVER)){
			dialect = new AnsiSqlDialect();
		}
		else if(url.toLowerCase().contains(JdbcConstants.MYSQL)){
			dialect = new MysqlDialect();
		}
		else if(url.toLowerCase().contains(JdbcConstants.POSTGRESQL)){
			dialect = new PostgreSqlDialect();
		}
		else{
			throw new RuntimeException("不支持的数据库！");
		}
		druidPlugin.addFilter(new StatFilter());
		druidPlugin.start();
		
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		//_MappingKit.mapping(arp);
		arp.setShowSql(showSql);
		arp.setDialect(dialect);
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(toLowerCase));
		arp.start();
	}
}